package com.yuanda.erp9.syn.execule.thread;


import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description: 通用的线程池(仅拥有一个核心线程数,用完快速释放资源)
 * @Params:
 * @Return:
 * @Author: Mr.myq
 * @Date: 2022/11/2916:59
 */
@Slf4j
public class CurrencyThreadPool {

    private CurrencyThreadPool() {
    }

    private volatile static ThreadPoolTaskExecutor threadPoolTaskExecutor;

    static final int CPU = Runtime.getRuntime().availableProcessors();
    static final int CORE_POOL_SIZE = 1;
    static final int MAXIMUM_POOL_SIZE = CPU * 3;
    static final int KEEP_ALIVE_TIME = 2000;
    static final int QUEUE_SIZE = 10000;


    /**
     * @Description: 单例
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/11/1517:18
     */
    public static ThreadPoolTaskExecutor getInstance() {
        if (threadPoolTaskExecutor == null) {
            synchronized (CurrencyThreadPool.class) {
                if (threadPoolTaskExecutor == null) {
                    initThreadPoolTaskExecutor();
                }
            }
        }
        return threadPoolTaskExecutor;
    }


    /**
     * @ClassName GlobalThreadPoolTask
     * @Description 初始化线程池
     * @Date 2022/11/15
     * @Author myq
     */
    private static void initThreadPoolTaskExecutor() {
        threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        threadPoolTaskExecutor.setMaxPoolSize(MAXIMUM_POOL_SIZE);
        threadPoolTaskExecutor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        threadPoolTaskExecutor.setQueueCapacity(QUEUE_SIZE);
        threadPoolTaskExecutor.setThreadNamePrefix("CURRENCY-THREAD-POOL-" );
        threadPoolTaskExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                log.error("触发拒绝策略 , 当前 活跃线程数 {} , 队列长度 {} ", executor.getActiveCount(), executor.getQueue().size());
            }
        });
        threadPoolTaskExecutor.initialize();
        log.info("--初始化全局线程池-- corePoolSize {} , maxPoolSize {} ,keepAliveSeconds {} ,queueCapacity {}", CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, QUEUE_SIZE);
    }


}
